import React, { useState, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Typography, Spin, Divider, Tag, Card, Space, Button, Result } from 'antd';
import { BookOutlined, ClockCircleOutlined, TagOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { useTheme } from '../../context/ThemeContext';
import { get as getArticle } from '../../api/articleController';

const { Title, Paragraph, Text } = Typography;

export const ArticleDetail: React.FC = () => {
    const [searchParams] = useSearchParams();
    const articleId = searchParams.get('id');
    const [article, setArticle] = useState<API.Article | null>(null);
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<string | null>(null);
    const { theme: currentTheme } = useTheme();
    const isInk = currentTheme === 'ink';

    useEffect(() => {
        if (!articleId) {
            setError('文章ID不存在');
            setLoading(false);
            return;
        }

        const fetchArticleDetail = async () => {
            try {
                setLoading(true);
                
                // 使用API请求获取文章详情
                // 确保将articleId作为字符串传递给API
                const result = await getArticle({ 
                    id: articleId 
                } as any); // 使用类型断言避免类型错误
                
                if (result?.data?.code === 0 && result?.data?.data) {
                    setArticle(result.data.data);
                } else {
                    setError(result?.data?.msg || '获取文章详情失败');
                }
            } catch (err) {
                console.error('获取文章详情出错:', err);
                setError('获取文章详情出错');
            } finally {
                setLoading(false);
            }
        };

        fetchArticleDetail();
    }, [articleId]);

    const goBack = () => {
        window.history.back();
    };

    if (loading) {
        return (
            <div style={{ 
                display: 'flex', 
                justifyContent: 'center', 
                alignItems: 'center', 
                height: '100vh',
                background: '#f5f5f5'
            }}>
                <Spin size="large" tip="加载文章中..." />
            </div>
        );
    }

    if (error || !article) {
        return (
            <Result
                status="404"
                title="文章不存在"
                subTitle={error || '未找到该文章或文章已被删除'}
                extra={
                    <Button type="primary" onClick={goBack}>
                        返回上一页
                    </Button>
                }
            />
        );
    }

    const formatDate = (dateString?: string) => {
        if (!dateString) return '';
        const date = new Date(dateString);
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    };

    return (
        <div 
            style={{ 
                padding: '20px', 
                maxWidth: '1000px', 
                margin: '0 auto',
                minHeight: '100vh',
                background: 'white'
            }}
            className="page-transition"
        >
            <Button 
                icon={<ArrowLeftOutlined />} 
                onClick={goBack}
                style={{ 
                    marginBottom: '20px',
                    color: isInk ? '#1677ff' : '#ff4d4f' 
                }}
                className="transition-all"
            >
                返回列表
            </Button>

            <Card 
                bordered={false}
                style={{ 
                    boxShadow: '0 2px 12px rgba(0, 0, 0, 0.08)',
                    borderRadius: isInk ? '8px' : '16px'
                }}
                className="card-hover"
            >
                <Space direction="vertical" size="large" style={{ width: '100%' }}>
                    <div>
                        <Title 
                            level={2} 
                            style={{ 
                                marginBottom: '8px',
                                color: isInk ? '#1677ff' : '#ff4d4f',
                                fontFamily: 'var(--font-family)'
                            }}
                        >
                            <BookOutlined style={{ marginRight: '12px' }} />
                            {article.title}
                        </Title>

                        <Space size="middle" wrap style={{ marginBottom: '16px' }}>
                            {article.createTime && (
                                <Text type="secondary" style={{ fontFamily: 'var(--font-family)' }}>
                                    <ClockCircleOutlined style={{ marginRight: '4px' }} />
                                    创建时间: {formatDate(article.createTime)}
                                </Text>
                            )}
                            
                            {article.updateTime && article.updateTime !== article.createTime && (
                                <Text type="secondary" style={{ fontFamily: 'var(--font-family)' }}>
                                    <ClockCircleOutlined style={{ marginRight: '4px' }} />
                                    更新时间: {formatDate(article.updateTime)}
                                </Text>
                            )}
                        </Space>
                    </div>

                    <Divider style={{ margin: '8px 0' }} />

                    {article.tagNames && (
                        <div>
                            <Space align="center">
                                <TagOutlined style={{ color: isInk ? '#1677ff' : '#ff4d4f' }} />
                                <Text strong style={{ fontFamily: 'var(--font-family)' }}>标签:</Text>
                                <Space size={[8, 8]} wrap>
                                    {article.tagNames.split(',').map((tag, index) => (
                                        <Tag 
                                            key={index}
                                            color={isInk ? 'blue' : 'volcano'}
                                            style={{ 
                                                borderRadius: isInk ? '4px' : '12px',
                                                padding: '3px 8px',
                                                fontFamily: 'var(--font-family)'
                                            }}
                                            className="file-tag-appear"
                                        >
                                            {tag.trim()}
                                        </Tag>
                                    ))}
                                </Space>
                            </Space>
                        </div>
                    )}

                    <Divider style={{ margin: '12px 0 20px' }} />

                    <div 
                        className="article-content"
                        style={{ 
                            padding: '8px 4px',
                            lineHeight: '1.8',
                            fontSize: '16px',
                            color: 'rgba(0, 0, 0, 0.85)',
                            fontFamily: 'var(--font-family)'
                        }}
                    >
                        {article.content ? (
                            <div dangerouslySetInnerHTML={{ __html: article.content }} />
                        ) : (
                            <Paragraph style={{ fontFamily: 'var(--font-family)' }}>
                                无内容
                            </Paragraph>
                        )}
                    </div>
                </Space>
            </Card>
        </div>
    );
}; 